<!--
 * @Author: LiYuan
 * @Date: 2021-04-02 17:07:21
 * @LastEditTime: 2024-03-21 18:46:31
 * @LastEditors: 铃兰 wanglili@publink.cn
 * @Description: 
 * You build it, You run it.
-->
<template>
  <div class="event-fields-form">
    <!-- 视图 -->
    <div v-if="!isEdit" class="fields-view-form">
      <form-view ref="formViewRef" :fields="fields" :value="value"></form-view>
    </div>
    
    <!-- 编辑 -->
    <div v-else class="edit-fields-form">
      <form-builder v-if="init" ref="formEditRef" mode="eventReceipt" :fields="fields" :value="value" @update="update" formEditingMode="edit" @getDeleteFiles="getDeleteFiles"></form-builder>
      <div class="btn-box" v-if="workEvent.inApprove != 1">
        <el-button @click="draftSave" :disabled="loading">{{$t('common.base.temporaryStorage')}}</el-button>
        <el-button type="primary" @click="handleSave" :disabled="loading">{{$t('common.base.finish')}}</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import * as EventApi from '@src/api/EventApi.js';

import _ from 'lodash';
import * as FormUtil from '@src/component/form/util'
import * as util from '@src/modules/event/util/event'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormSubmitTime } = useFormTimezone()
import { scrollIntoFirstRequireDom } from '@src/util/dom';

export default {
  name: 'event-fields-form',
  props: {
    workEvent: {
      type: Object,
      default: ()=> {}
    },
    workDraftEvent: {
      type: Object,
      default: ()=> {}
    },
    fields: {
      type: Array,
      default: ()=> []
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    }
  },

  async created() {
    let value = {}
    this.init = false
    if(this.isEdit) {
      // 处理富文本
      const workDraftEvent = await FormUtil.initRichTextContent(this.fields, this.workDraftEvent )
      let form = util.packToForm(this.fields, workDraftEvent);
      value = FormUtil.initialize(this.fields, form);
    } else {
      if(this.type === 'approveReceiptInfo') { // 回执审批信息
        value = this.workDraftEvent
      } else if(this.type === 'receiptInfo') { // 回执信息
        value = this.workEvent
      }
    // 处理富文本
    value = await FormUtil.initRichTextContent(this.fields, value)

    }
    this.value = value
    this.init = true
  },
  
  data() {
    return {
      value: {},
      loading: false,
      init: true,
      needServerDeleFiles:[]
    }
  },
  methods: {
    // 暂存
    draftSave() {
      // 处理国际化时间转换
      let formValue = disposeFormSubmitTime(this.fields, this.value)
      // 如果没有workDraft，id会为空
      let params = Object.assign(_.cloneDeep(this.workEvent), util.packToEvent(this.fields, formValue), {id: this.workEvent.id})
      
      params = this.globalFormSubmissionDataProcessingHandler(this.fields, params)
      
      if(this.needServerDeleFiles.length){
        params.deleteFiles = this.needServerDeleFiles
      }

      this.loading = true
      EventApi.eventSaveReceiptDraft(params)
        .then(res => {
          if(res.status==0) {
              this.$notify({
                title: this.$t('common.base.success'),
                message: this.$t('common.base.temporarySaveSuccess'),
                type: 'success'
              });
              this.needServerDeleFiles = []
            } else {
              this.$notify({
                title: this.$t('common.base.error'),
                message: res.message,
                type: 'error'
              });
            }
        })
        .finally(()=> {this.loading = false})
    },

    // 完成
    async handleSave() {
      try {
        // 完成事件回执校验附加组件必填
        let checkFinshNodeRes = await EventApi.eventCheckNotNullForCard({
          id: this.workEvent.id,
          flow: 'finish'
        })
        if(checkFinshNodeRes.status != 0) return this.$notify({
          title: this.$t('common.base.error'),
          message: checkFinshNodeRes.message,
          type: 'error'
        });

      const that = this
      this.$refs.formEditRef.validate(false)
        .then(vali => {
          scrollIntoFirstRequireDom(this.$refs.formEditRef)
          if(vali) {
            this.$confirm(this.$t('event.detail.components.eventButtonGroup.text14'), this.$t('common.base.toast'), {
              confirmButtonText: this.$t('common.base.makeSure'),
              cancelButtonText: this.$t('common.base.cancel'),
              type: 'warning',
            })
              .then(async () => {
                // 处理国际化时间转换
                let formValue = disposeFormSubmitTime(this.fields, this.value)
                let params = Object.assign(_.cloneDeep(that.workEvent), util.packToEvent(that.fields, formValue), {id: this.workEvent.id})
                params = this.globalFormSubmissionDataProcessingHandler(that.fields, params)

                if (this.needServerDeleFiles.length) {
                  params.deleteFiles = this.needServerDeleFiles
                }

                // 判断是否有高级审批
                const result = await this.checkNeedVipApprove(params)
                if (result?.needVipApprove) {
                  return this.$emit('needVipApprove', result)
                }

                EventApi.eventFinish(params)
                    .then(res => {
                      if (res.status == 0) {
                        that.$emit('reloadTab')
                        window.location.href = `${this.$resourcePrefix}/event/view/${that.workEvent.id}`
                      } else {
                        if (res.message == 'needwait') {
                          that.$message.warning(this.$t('event.detail.components.eventButtonGroup.text13'))
                        } else {
                          if (res.data != null) {
                            that.$emit('needApprove', res.data)
                          } else {
                            this.$message.warning(res.message)
                          }
                        }
                      }
                    })
              })
            .catch(() => { });
          }
        })
      } catch (error) {
        console.log(error)    
      }
    },

    // 判断是否需要高级审批
    async checkNeedVipApprove(params) {
      try {
        const { success, result, message} = await EventApi.checkEventNeedVipApprove({
          eventId: this.workEvent.id,
          eventTemplateId: this.workEvent.templateId,
          action: 'finish',
          params,
        });

        if(!success) {
          this.$message.error(message);
          throw new Error(message);
        }

        return result;
      } catch (e) {
        throw new Error(e)
      }
    },

    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      let value = this.value;
      this.$set(value, fieldName, newValue);
      this.$emit('input', value);
    },
    getDeleteFiles(files){
      this.needServerDeleFiles = [...this.needServerDeleFiles,...files]
    }
  }
}
</script>

<style lang="scss" scoped>
.event-fields-form {
  .el-form-item--small.el-form-item {
    margin-bottom: 0;
  }
}
</style>